package com.bruce.tool.mail.core;

import com.bruce.tool.mail.config.MailConfig;
import com.bruce.tool.mail.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 7:46 PM 2018/12/8
 */
@Component("mailAdapter")
public class MailAdapter {

    @Autowired
    private MailConfig mailConfig;

    private Mail mail = Mail.create();

    private void init(){
        mail.host(mailConfig.getHost())
                .auth(mailConfig.getUsername(), mailConfig.getPassword())
                .secret(mailConfig.getSecret())
                .copy(mailConfig.getCopy())
                .to(mailConfig.getTo())
        ;
    }

    public MailAdapter setTo(String to){
        mailConfig.setTo(to);
        return this;
    }

    public MailAdapter setCopy(String copy){
        mailConfig.setCopy(copy);
        return this;
    }

    public MailAdapter setSecret(String secret){
        mailConfig.setSecret(secret);
        return this;
    }

    public MailAdapter addTo(String to){
        mailConfig.setTo(mailConfig.getTo()+ Constants.SPLIT_SEPARATOR + to);
        return this;
    }

    public MailAdapter addCopy(String copy){
        mailConfig.setCopy(mailConfig.getCopy()+ Constants.SPLIT_SEPARATOR + copy);
        return this;
    }

    public MailAdapter addSecret(String secret){
        mailConfig.setSecret(mailConfig.getSecret()+ Constants.SPLIT_SEPARATOR + secret);
        return this;
    }

    public MailAdapter setSubject(String subject){
        this.mail.subject(subject);
        return this;
    }

    public MailAdapter setContent(String content){
        this.mail.content(content);
        return this;
    }

    public MailAdapter addPicture(String pid, String url){
        this.mail.picture(pid,url);
        return this;
    }

    public MailAdapter addPictures(Map<String, String> pictures){
        this.mail.pictures(pictures);
        return this;
    }

    public MailAdapter addAttachment(String pid, String url){
        this.mail.attachment(pid,url);
        return this;
    }

    public MailAdapter addAttachments(Map<String, String> attachments){
        this.mail.attachments(attachments);
        return this;
    }

    public MailAdapter addByteAttachment(String pid, byte[] bytes){
        this.mail.byteAttachment(pid,bytes);
        return this;
    }

    public MailAdapter addByteAttachments(Map<String, byte[]> attachments){
        this.mail.byteAttachments(attachments);
        return this;
    }

    /**是否追加附件内容到邮件正文中:仅仅支持2003版的Excel**/
    public MailAdapter appendToContent(boolean append) {
        this.mail.appendToContent(append);
        return this;
    }

    /**执行邮件发送操作**/
    public void send(){
        this.init();
        this.mail.send();
    }
}
